import { authLogin, authLogout, authOrg, authUserMe } from '@/common/api/auth'
import { STORAGE_AUTH, STORAGE_TOKEN_REFRESH } from '@/common/plugins/constant'
import { addressFromLevel } from '@vimi/utils-tool'
const removeUser = commit => {
  commit('user', {})
  localStorage.removeItem(STORAGE_TOKEN_REFRESH)
  localStorage.removeItem(STORAGE_AUTH)
}
const getUserRegionLevel = level => {
  return +level || 0
}

const state = {
  login: {},
  user: {},
  org: {},
}

const getters = {
  login: state => state.login,
  user: state => state.user,
  org: state => state.org,
  job: state => state.user.job,
  userId: state => state.user.userId,
  clientId: state => state.org.clientId,
}

const actions = {
  /**
   * 登录
   *
   * @param {Object} param0
   * @param {Object} loginInfo
   * @param {Function} validator
   */
  async login({ commit }, params) {
    const { data, validator } = params
    const res = await authLogin(data)
    const resData = res.data || {}

    // 需要登录成功后再验证是否可以查看平台内容，验证失败则清除cookie
    if (typeof validator === 'function' && !validator(resData)) {
      this.dispatch('logout', false)
      throw new Error('平台验证失败，请用该平台账号登录')
    }

    // 登录信息保存
    const { access_token, refresh_token, ...login } = resData // eslint-disable-line

    login.orgRegionLever = getUserRegionLevel(login.orgRegionLever)
    login.queryAddressCode = addressFromLevel(resData.addressCode, resData.orgRegionLever)

    localStorage.setItem(STORAGE_AUTH, JSON.stringify(login))
    commit('login', login)
    return resData
  },

  /**
   * 获取用户信息
   *
   * @param {Object} param0
   */
  async getMe({ commit, rootGetters }) {
    const res = await authUserMe()
    const data = res.data || {}

    data.orgRegionLever = getUserRegionLevel(data.orgRegionLever)
    data.queryAddressCode = addressFromLevel(
      rootGetters.org.addressCode || data.addressCode,
      data.orgRegionLever
    )

    data.scopeArr = (data.scopes || '').split('|').filter(it => it)

    data.isApprovalRep = +(data.isApprovalRep || 0)
    data.isProcessPointBus = +(data.isProcessPointBus || 0)
    data.isProcessPointRisk = +(data.isProcessPointRisk || 0)
    data.isReporter = +(data.isReporter || 0)

    commit('user', data)
    return data
  },

  /**
   * 获取组织信息
   *
   * @param {Object} param0
   */
  async getOrg({ commit, rootGetters }) {
    const res = await authOrg()
    const data = res.data || {}

    commit('user', {
      ...rootGetters.user,
      queryAddressCode: addressFromLevel(data.addressCode, rootGetters.user.orgRegionLever),
    })

    commit('org', data)
    return data
  },

  /**
   * 调用接口登出
   *
   * @param {Object} param0
   */
  async logout({ commit }) {
    const res = await authLogout()
    removeUser(commit)
    return res
  },

  /**
   * 不调用接口，前端登录
   */
  fedLogout({ commit }) {
    return new Promise(resolve => {
      removeUser(commit)
      resolve()
    })
  },
}

const mutations = {
  login: (state, payload) => (state.login = payload),
  user: (state, payload) => (state.user = payload),
  org: (state, payload) => (state.org = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
